package com.feihong.txgw.ui.activity.Nearby;

import android.Manifest;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.LogUtils;
import com.feihong.txgw.R;
import com.feihong.txgw.http.HttpTools;
import com.feihong.txgw.http.RefreshToken;
import com.feihong.txgw.message.LocationMessage;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.bean.location.LocationInfo;
import com.feihong.txgw.model.bean.user.CityInfo;
import com.feihong.txgw.ui.activity.Nearby.webviewinterface.MenDianDetailWebviewInterFace;
import com.feihong.txgw.ui.activity.base.BaseActivity;
import com.feihong.txgw.ui.activity.product.DaoHangActivity;
import com.feihong.txgw.ui.activity.product.ProductListActivity;
import com.feihong.txgw.utils.LocationCallBack;
import com.feihong.txgw.utils.LocationTools;
import com.feihong.txgw.utils.UserLoginInfo;
import com.feihong.txgw.utils.manage.ThreadPoolManager;
import com.feihong.txgw.utils.sign.SignToken;
import com.feihong.txgw.view.WebView4Scroll;
import com.just.agentweb.AgentWeb;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;

import butterknife.BindView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by PVer on 2017/8/8.
 * 附近门店详情页
 */

@RuntimePermissions
public class MenDianDetailActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_pagetitle)
    TextView txtPagetitle;
    @BindView(R.id.top_back_layout)
    RelativeLayout topBackLayout;
    @BindView(R.id.webviewframe)
    RelativeLayout webviewframe;
    @BindView(R.id.messagewListSwiperefreshlayout)
    SwipeRefreshLayout swiperefreshlayout;

    @BindView(R.id.connect_net_error_layout)
    LinearLayout mConnectErrorLayout;
    @BindView(R.id.re_query_data_layout)
    LinearLayout mRequeryDataBtn;
    private AgentWeb mAgentWeb;
    private String citycode;
    private String store_id, store_name;
    private String lng;
    private String lat;
    private String url;
    private String city;
    private AgentWeb.PreAgentWeb mPreAgentWeb;

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if(activityIsDestory()){
                return;
            }
            switch (msg.what) {
                case 10:
                    loadPage();
                    break;
                case 11:
                    mConnectErrorLayout.setVisibility(View.VISIBLE);
                    break;
                default:break;
            }
        }
    };

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_messagelist;
    }

    private void refreshToken() {
        ThreadPoolManager.getInstance().execute( new Runnable() {
            @Override
            public void run() {

                Message message = Message.obtain();
                if (RefreshToken.getInstance().RetrofitRefreshTokenForGet()) {
                    message.what = 10;
                }else {
                    message.what = 11;
                }
                mHandler.sendMessage(message);
            }
        });
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        Intent store = getIntent();
        store_id = store.getStringExtra("store_id");
        store_name = store.getStringExtra("store_name");

        MenDianDetailActivityPermissionsDispatcher.onMenDianLocationPermissQueryWithCheck(this);
        setBackButtonFinish();

        if (!TextUtils.isEmpty(store_name)) {
            setPageTitle(store_name);
        } else {
            setPageTitle("门店详情");
        }
        mRequeryDataBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mConnectErrorLayout.setVisibility(View.GONE);
                refreshToken();
            }
        });
        //设置刷新时动画的颜色，可以设置4个
        swiperefreshlayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
        swiperefreshlayout.setColorSchemeResources(R.color.appRed,
                android.R.color.holo_red_light, android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        swiperefreshlayout.setProgressViewOffset(false, 0, (int) TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources()
                        .getDisplayMetrics()));
        swiperefreshlayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        loadPage();
                    }
                }, 200);
            }
        });
        //同步 Cookie
        //AgentWebConfig.syncCookies("http://www.djml.com","ID=XXXX")
        swiperefreshlayout.setRefreshing(true);
        WebView4Scroll webView4Scroll = new WebView4Scroll(MenDianDetailActivity.this, swiperefreshlayout);
        webView4Scroll.setVerticalScrollBarEnabled(false);
        mPreAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(webviewframe, new RelativeLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebChromeClient(mWebChromeClient).setWebView(webView4Scroll)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_errorlayout,R.id.agentweb_re_query_data_layout)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .createAgentWeb()
                .ready();
    }

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            swiperefreshlayout.setRefreshing(false);
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            //super.onReceivedSslError(view, handler, error);
            handler.proceed();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    };
    private WebChromeClient mWebChromeClient = new WebChromeClient() {
    };

    @Override
    public void bindData() {
        // 安卓调用js(传入js方法名)
        // mAgentWeb.getJsEntraceAccess().quickCallJs("");
    }

    private void loadPage() {
        lat = UserLoginInfo.getUserCityInfo().getLatitude();
        lng = UserLoginInfo.getUserCityInfo().getLongitude();
        citycode = UserLoginInfo.getUserCityInfo().getCityCode();
        city = UserLoginInfo.getUserCityInfo().getCityName();
        // Activity用法
        HashMap<String, String> prams = new HashMap<>();
        prams.put("store_id", store_id);
        prams.put("lng", lng);
        prams.put("lat", lat);
        prams.put("citycode", citycode);
        prams.put("city", city);
        String params = new SignToken().setSigen(prams);
        url = HttpTools.MENDIAN_DETAIL + "?" + params;
        mAgentWeb = mPreAgentWeb.go(url);
        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new MenDianDetailWebviewInterFace(mAgentWeb, this, new ActionCallBack() {
            @Override
            public void navigate(String addcartinfo) {
                naviGate(addcartinfo);
            }

            /*            门店具体的位置      */
            @Override
            public void storeAddr(String addcartinfo) {
                storeaddr(addcartinfo);
            }

            /*            店内详情      */
            @Override
            public void storeDetail(String addcartinfo) {
                storeDeTail(addcartinfo);
            }
        }));
        //屏蔽长按弹出复制按钮
        mAgentWeb.getWebCreator().getWebView().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

        mAgentWeb.getWebLifeCycle();
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public interface ActionCallBack {
        public void navigate(String addcar);

        public void storeAddr(String addcar);

        public void storeDetail(String addcar);

    }

    /*导航*/
    private void naviGate(String json) {
        if (lng == null || lng.trim().length() == 0 || lat == null || lat.trim().length() == 0) {
            showSystemToast("数据错误！");
            return;
        } else {
            JSONObject obj = JSON.parseObject(json);
            String end_lng = obj.getString("arr_lng");
            String end_lat = obj.getString("arr_lat");
            String start_lat = obj.getString("lat");
            String start_lng = obj.getString("lng");
            String endName = obj.getString("addr");

            startActivity(new Intent(MenDianDetailActivity.this, DaoHangActivity.class).putExtra("end_lng", end_lng)
                    .putExtra("end_lat", end_lat).putExtra("start_lat", start_lat).putExtra("start_lng", start_lng).putExtra("addr",endName));
        }
    }

    /*    定位  (确定门店的位置)   */
    private void storeaddr(String json) {
        if (lng == null || lng.trim().length() == 0 || lat == null || lat.trim().length() == 0) {
            showSystemToast("数据错误！");
            return;
        } else {
            JSONObject obj = JSON.parseObject(json);
            //当前经纬度
            String end_lng = obj.getString("lng");
            String end_lat = obj.getString("lat");
            //门店地址
            String start_lat = obj.getString("start_lat");
            String start_lng = obj.getString("start_lng");

            String endName = obj.getString("addr");

            startActivity(new Intent(MenDianDetailActivity.this, DaoHangActivity.class).putExtra("end_lng", end_lng)
                    .putExtra("end_lat", end_lat).putExtra("start_lat", start_lat).putExtra("start_lng", start_lng).putExtra("addr",endName));

        }
    }

    /*    店内详情   */
    private void storeDeTail(String json) {

        if (json == null || json.length() == 0) {
            showSystemToast("数据错误！");
            return;
        } else {
            JSONObject obj = JSON.parseObject(json);
            String store_id = obj.getString("store_id");
            if (store_id != null) {
                startActivity(new Intent(MenDianDetailActivity.this, ProductListActivity.class)
                        .putExtra("store_id", store_id));
            }
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // NOTE: delegate the permission handling to generated method
        MenDianDetailActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }


    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void onMenDianLocationPermissQuery() {
        LocationTools locationTool = new LocationTools(this, new LocationCallBack() {
            @Override
            public void successGetLocation(LocationInfo info) {
                if (info != null) {
                    LogUtils.i("定位", info.toString());
                    CityInfo cityInfo = new CityInfo();
                    cityInfo.setCityCode(info.getCityCode());
                    cityInfo.setCityName(info.getCity());
                    cityInfo.setLatitude(info.getLatitude() + "");
                    cityInfo.setLongitude(info.getLongitude() + "");

                    if (!TextUtils.isEmpty(info.getCity().toString())) {

                    }
                    if (UserLoginInfo.setUserCityInfo(cityInfo)) {
                        Log.i(TAG, "successGetLocation: 设置成功");
                        EventBus.getDefault().post(new LocationMessage());
                    } else {
                        Log.i(TAG, "successGetLocation: 设置失败");
                        showSystemToast("设置定位信息失败!");
                    }
                }
                refreshToken();
            }

            @Override
            public void error(String error) {
                LogUtils.i(TAG+ ": error: 定位失败:" + error);
                switch (error){
                    case "4":
                    case "5":
                        showSystemToast("定位失败,请检查网络");
                        break;
                    case "12":
                        showSystemToast("请在设备的设置中开启app的定位权限");
                        break;
                    case "13":
                        showSystemToast("定位失败,请检查网络、GPS是否开启以及定位权限是否开启");
                        break;
                    case "14":
                        showSystemToast("定位失败,请到相对开阔的露天场所再次尝试");
                        break;
                    case "18":
                        showSystemToast("定位失败,建议手机关闭飞行模式，并打开WIFI开关");
                        break;
                    case "19":
                        showSystemToast("定位失败,建议手机插上sim卡，打开WIFI开关");
                        break;
                    default:break;
                }
                finish();
            }
        });
        locationTool.startLocation();
    }

    @OnShowRationale({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void onMenDianLocationPermissRationale(final PermissionRequest request) {
        // NOTE: Show a rationale to explain why the permission is needed, e.g. with a dialog.
        // Call proceed() or cancel() on the provided PermissionRequest to continue or abort
        request.proceed();
//        new AlertDialog.Builder(this)
//                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(@NonNull DialogInterface dialog, int which) {
//                        request.proceed();
//                    }
//                })
//                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(@NonNull DialogInterface dialog, int which) {
//                        request.cancel();
//                    }
//                })
//                .setCancelable(false)
//                .setMessage("请允许获取位置权限")
//                .show();
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void onMenDianLocationPermissionDenied() {
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mHandler != null && mHandler.getLooper() == Looper.getMainLooper()){
            mHandler.removeCallbacksAndMessages(null);
        }
        if(mAgentWeb != null){
            mAgentWeb.destroy();
        }
    }
}
